package dfs;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * 给定一个数组 candidates 和一个目标数 target ，找出 candidates 中所有可以使数字和为 target 的组合。
 * https://leetcode-cn.com/problems/combination-sum-ii/
 *
 * @author: luo
 * @email: luo@nyist.edu.cn
 * @date: 2021/1/26 11:03
 */
public class CombinationSum2 {
    public static void main(String[] args) {
        int[] candidates = {10, 1, 2, 7, 6, 1, 5};
        int target = 8;

        System.out.println(combinationSum2(candidates, target));
    }


    private static List<List<Integer>> list = new LinkedList<>();

    public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        backtracking(target, candidates, new LinkedList<>(), 0);
        return list;
    }

    private static void backtracking(int n, int[] candidates, LinkedList<Integer> nums, int index) {
        if (n == 0) {
            list.add(new ArrayList<>(nums));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            if (candidates[i] > n) {
                break;
            }
            if (i != index && candidates[i] == candidates[i - 1]) {
                continue;
            }
            nums.addLast(candidates[i]);
            backtracking(n - candidates[i], candidates, nums, i + 1);
            nums.removeLast();
        }
    }
}
